package com.imooc.web.controller;

import com.imooc.dto.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 * Author:   yangdc
 * Date:     2018/9/3 3:08
 */
@RestController
@RequestMapping("file")
public class FileController {
    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {

        System.out.println("name: " + file.getName());
        System.out.println("filename: " + file.getOriginalFilename());
        String filePath = System.getProperty("user.home") + File.separator + new Date().getTime() + ".txt";
        File localFile = new File(filePath);
        file.transferTo(localFile);

        return new FileInfo(filePath);
    }

    @GetMapping("{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = System.getProperty("user.home") + File.separator + id + ".txt";
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        try (
                InputStream is = new FileInputStream(file);
                OutputStream os = response.getOutputStream();
        ) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");

            IOUtils.copy(is, os);
            os.flush();
        }
    }
}
